#include "verifycodewidget.h"
#include <qdatetime.h>

VerifyCodeWidget::VerifyCodeWidget(QWidget *parent)
    : QWidget(parent),randomGenerator(QDateTime::currentMSecsSinceEpoch()),verifyCode(generateVerifyCode())
{
}

QString VerifyCodeWidget::generateVerifyCode()
{
    QString ret;
    for(int i = 0; i< 4 ;++i)
    {
        int init = 'A';

        ret += static_cast<QChar>(randomGenerator.generate() % 26 + init);
    }

    return ret;

}

void VerifyCodeWidget::refreshVerifyCode()
{
    verifyCode = generateVerifyCode();
    this->update();
}

bool VerifyCodeWidget::checkVerifyCode(const QString &verifyCode)
{
    return this->verifyCode.compare(verifyCode,Qt::CaseInsensitive) == 0;
}

void VerifyCodeWidget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    QPen pen;
    QFont font("楷体",25,QFont::Bold,true);
    painter.setFont(font);
    // 画点: 添加随机噪点
    for(int i = 0; i < 300; i++)
    {
        pen = QPen(QColor(randomGenerator.generate() % 256,
                          randomGenerator.generate() % 256, randomGenerator.generate() % 256));
        painter.setPen(pen);
        painter.drawPoint(randomGenerator.generate() % 180,
                          randomGenerator.generate() % 80);
    }
    // 画线: 添加随机⼲扰线
    for(int i = 0; i < 10; i++)
    {
        pen = QPen(QColor(randomGenerator.generate() % 256,
                          randomGenerator.generate() % 256, randomGenerator.generate() % 256));
        painter.setPen(pen);
        painter.drawLine(randomGenerator.generate() % 180,
                         randomGenerator.generate() % 80, randomGenerator.generate() % 180,
                         randomGenerator.generate() % 80);
    }
    // 绘制验证码
    for(int i = 0; i < verifyCode.size(); i++)
    {
        pen = QPen(QColor(randomGenerator.generate() % 255,
                          randomGenerator.generate() % 255, randomGenerator.generate() % 255));
        painter.setPen(pen);
        painter.drawText(5+20*i, randomGenerator.generate() % 10, 30, 30,
                         Qt::AlignCenter, QString(verifyCode[i]));
    }
}

void VerifyCodeWidget::mousePressEvent(QMouseEvent *event)
{
    refreshVerifyCode();
}
